import type { RuleObject, Rule as ValidationRule } from 'ant-design-vue/lib/form/interface';
import { computed, unref, Ref } from 'vue';
import { useI18n } from '@/hooks/web/useI18n';

/** 使用表单验证 */
export function useFormValid<T extends Object = any>(formRef: Ref<any>) {
  /** 验证表单 */
  async function validForm() {
    const form = unref(formRef);
    if (!form) return;
    const data = await form.validate();
    return data as T;
  }

  return { validForm };
}

/** 使用表单规则 */
export function useFormRules(formData?: Recordable) {
  const { t } = useI18n();

  const getPasswordFormRule = computed(() => createRule(t('sys.login.passwordPlaceholder')));
  //const getConfirmPasswordFormRule = computed(() => createRule(t('sys.login.confirmPasswordPlaceholder')));

  /**
   * 验证确认密码
   * @param password 密码
   * @returns
   */
  const validateConfirmPassword = (password: string) => {
    return async (_: RuleObject, value: string) => {
      if (!value) {
        return Promise.reject(t('sys.login.confirmPasswordPlaceholder'));
      }
      if (value !== password) {
        return Promise.reject(t('sys.login.diffPwd'));
      }
      return Promise.resolve();
    };
  };

  /** 获取表单规则 */
  const getFormRules = computed((): { [k: string]: ValidationRule | ValidationRule[] } => {
    const passwordFormRule = unref(getPasswordFormRule);
    //const confirmPasswordFormRule = unref(getConfirmPasswordFormRule);

    return {
      newPassword: passwordFormRule,
      confirmPassword: [
        { validator: validateConfirmPassword(formData?.newPassword), trigger: 'change' },
      ],
    };
  });
  return { getFormRules };
}

/** 创建规则 */
function createRule(message: string): ValidationRule[] {
  return [
    {
      required: true,
      message,
      trigger: 'change',
    },
  ];
}
